<template>
	<view class="select-container">
		<!-- 搜索框和 Tabs -->
		<view class="header">
			<view class="search-bar">
				<up-search v-model="searchValue" placeholder="输入姓名或班组名称" shape="square" clearable :show-action="false" />
			</view>

			<up-tabs :list="tabList" :current="currentTab" @change="tabsChange" lineColor="#2979ff"
				itemStyle="background:#fff;height: 80rpx;width: 100%;border-bottom: 1rpx solid #f5f5f5;" />
		</view>

		<!-- 用户列表 -->
		<view class="list-container" v-if="currentTab === 0">
			<up-checkbox-group v-model="selectedUsers" placement="row">
				<view class="list-item" v-for="item in filteredUserList" :key="item.id">
					<up-checkbox :name="item.id" :label="item.text" label-size="16" />
				</view>
			</up-checkbox-group>
		</view>

		<!-- 班组列表 -->
		<view class="list-container" v-if="currentTab === 1">
			<up-radio-group v-model="selectedTeam">
				<view class="list-item" v-for="item in filteredTeamList" :key="item.id">
					<up-radio :name="item.id" :label="item.maintenance_team_name" label-size="16" />
					<view class="team-members" v-if="item.maintenance_team_user_name">
						{{ item.maintenance_team_user_name }}
					</view>
				</view>
			</up-radio-group>
		</view>

		<!-- 底部按钮 -->
		<view class="footer">
			<up-button type="default" @click="goBack">取消</up-button>
			<up-button type="primary" @click="confirm">确定</up-button>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import http from '@/api/request'

	const searchValue = ref('')
	const currentTab = ref(0)
	const tabList = ref([{
			name: '用户列表'
		},
		{
			name: '维保班组'
		}
	])

	const userList = ref([])
	const teamList = ref([])

	const selectedUsers = ref([])
	const selectedTeam = ref("")

	const repair_id = ref("")
	const repair_code = ref("")

	onLoad((params) => {
		repair_id.value = params.id;
		repair_code.value = params.repair_code;
	})


	const filteredUserList = computed(() => {
		if (!searchValue.value) return userList.value
		return userList.value.filter(item => item.text?.includes(searchValue.value))
	})

	const filteredTeamList = computed(() => {
		if (!searchValue.value) return teamList.value
		return teamList.value.filter(item =>
			item.maintenance_team_name?.includes(searchValue.value) ||
			item.maintenance_team_user_name?.includes(searchValue.value)
		)
	})

	const tabsChange = (val) => {
		currentTab.value = val.index
	}

	// 请求所有用户
	const loadUserList = async () => {
		try {
			const res = await http.post('/api/module/GetViewTable', {
				code: 'Sys_GetUserNameById',
				allColumnFilter: true,
				filters: [],
				pageInput: {
					currentPage: 1,
					pageSize: 1000
				},
				permissionKey: ''
			})
			if (res.isSuccess && res.result?.viewTable) {
				userList.value = res.result.viewTable
			} else {
				userList.value = []
			}
		} catch (err) {
			console.error('获取用户失败', err)
			userList.value = []
		}
	}

	// 请求所有班组
	const loadTeamList = async () => {
		try {
			const res = await http.post('/api/module/GetViewTable', {
				code: 'getBaseMaintenanceTeam',
				allColumnFilter: true,
				filters: [{
					name: 'maintenance_team_status',
					value: 'ENABLE'
				}],
				pageInput: {
					currentPage: 1,
					pageSize: 1000
				},
				permissionKey: ''
			})
			if (res.isSuccess && res.result?.viewTable) {
				teamList.value = res.result.viewTable
			} else {
				teamList.value = []
			}
		} catch (err) {
			console.error('获取班组失败', err)
			teamList.value = []
		}
	}

	const confirm = () => {
		uni.showLoading({
			title: '提交中...'
		});

		let reqParam = {
			"id": repair_id.value,
			"repair_code": repair_code.value
		};

		if (currentTab.value === 0) {
			// 用户模式 - 将选中的用户ID用逗号连接
			reqParam["repair_personnel"] = selectedUsers.value.join(',');
			reqParam["repair_team"] = ''; // 用户模式不需要班组ID
		} else {
			// 班组模式 - 单选
			if (selectedTeam.value) {
				const team = teamList.value.find(item => item.id === selectedTeam.value);
				if (team) {
					reqParam["repair_personnel"] = team.maintenance_team_user;
					reqParam["repair_team"] = team.id;
				}
			}
		}

		http.post('/api/module/Invoke', {
			pageCode: "assetwarranty",
			params: {
				args: [{
						name: "interfaceCode",
						value: "Assetwarranty.assign"
					},
					{
						name: "repairMstr",
						value: reqParam
					}
				]
			},
			methodName: "assign"
		}).then(res => {
			uni.hideLoading();
			if (res.isSuccess) {
				uni.showToast({
					title: "指派成功",
					icon: 'success'
				});
				setTimeout(() => {
					goBack();
				}, 1500);
			} else {
				uni.showToast({
					title: res.error || '操作失败',
					icon: 'none'
				});
			}
		}).catch(() => {
			uni.hideLoading();
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
		});
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	onMounted(() => {
		loadUserList()
		loadTeamList()
	})
</script>
<style lang="scss" scoped>
	.select-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;

		.header {
			background-color: #fff;

			.search-bar {
				padding: 20rpx;
				border-bottom: 1rpx solid #f5f5f5;
			}
		}

		.list-container {
			flex: 1;
			background: #fff;

			.list-item {
				padding: 24rpx 30rpx;
				border-bottom: 1rpx solid #f5f5f5;

				.team-members {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
					margin-left: 60rpx;
				}
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			padding: 20rpx 30rpx;
			background-color: #fff;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			.up-button {
				flex: 1;
				margin: 0 10rpx;
			}
		}
	}
</style>